import { Component, ElementRef, ViewChild } from '@angular/core';
import {ICellEditorAngularComp} from '@ag-grid-community/angular';
import { ApesCityPickerComponent } from '@shared/apes/city-picker/apes-city-picker.component';

@Component({
  selector: 'apes-cell-city-picker',
  template: `
    <apes-city-picker #picker
                      [(ngModel)]="inputValue"
                      [apesPlaceHolder]="placeholder()"
                      [level]="level"></apes-city-picker>
      `,
  styles: []
})
export class EditorCityPickerComponent implements ICellEditorAngularComp {

  inputValue: any;
  params: any;
  _level: any;
  @ViewChild('picker', { read: ApesCityPickerComponent, static: true }) picker: ApesCityPickerComponent;
  constructor() {
  }

  agInit(params: any): void {
    this.params = params;
    this.inputValue = params.value;
    if (this.params.hasOwnProperty('colDef')) {
      this._level = this.params.colDef.level;
    } else {
      this._level = this.params['column']['colDef'].level;
    }
  }

  ngAfterViewInit() {
    setTimeout(()=>{
      this.picker.focus();
      this.picker.setMenuVisible(true);
    },300);
  }

  isPopup(): boolean {
    return false;
  }

  getValue(): any {
    let result;
    if (!this.inputValue) {
      result = {};
      this.params.value = {};
      this.params.data['renderAddr'] = '';
    } else {
      result = this.inputValue;
      this.params.value = this.inputValue;
      this.params.data['renderAddr'] = this.picker.labelRenderText;
    }
    return result;
  }

  get level() {
    return this._level || 'district';
  }

  placeholder() {
    return this.params.placeholder || '请选择';
  }
}
